<template>
  <view class="header">
    <input
      type="text"
      confirm-type="search"
      v-model="inputVal"
      @confirm="confirmHandler"
    />
    <icon class="search-icon" type="search" size="16"> </icon>
    <icon
      class="clear-icon"
      type="clear"
      size="16"
      color="#ccc"
      v-show="inputVal"
      @click="clearInput"
    >
    </icon>
  </view>
</template>

<script>
export default {
  props: ['query'],
  data () {
    return {
      // 输入框的值
      inputVal: ''
    }
  },
  watch: {
    // 当子prop有变化,更新data属性
    query (newValue) {
      this.inputVal = newValue
    }
  },
  methods: {
    // 清空输入框
    clearInput () {
      this.inputVal = ''
    },
    // 点击键盘右下角按钮时触发，事件传给父亲
    confirmHandler () {
      // 如果输入框的值为空,不触发搜索
      if (!this.inputVal) {
        return
      }
      this.$emit('search', this.inputVal)
    }
  }
}
</script>

<style lang="less" scoped>
.header {
  height: 120rpx;
  background-color: #eee;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;

  input {
    background-color: #fff;
    height: 60rpx;
    width: 720rpx;
    padding-left: 74rpx;
    box-sizing: border-box;
  }

  .search-icon {
    position: absolute;
    left: 44rpx;
  }

  .clear-icon {
    position: absolute;
    right: 44rpx;
    z-index: 100;
    left: auto;
  }
}
</style>
